package com.qianbei.view;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.qianbei.R;
import com.qianbei.bean.GetBindBean;
import com.qianbei.bean.GetCouseBean;
import com.qianbei.common.base.BaseActivity;
import com.qianbei.common.base.MyApplication;
import com.qianbei.common.init.SetData;
import com.qianbei.common.net.control.ServerControl;
import com.qianbei.common.net.control.ServerResult;
import com.qianbei.common.net.okhttp.RequeastBean;
import com.qianbei.common.net.view.MsgAlert;
import com.qianbei.common.net.view.ProgressDialog;
import com.qianbei.common.util.DeviceUtil;
import com.qianbei.view.orm.Course;
import com.qianbei.view.orm.CourseDao;
import com.qianbei.view.orm.DaoSession;
import com.qianbei.view.orm.RFIDDao;
import com.qianbei.view.orm.RequestPersistent;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnFocusChange;

public class CourseActivity extends BaseActivity implements View.OnFocusChangeListener {


    @Bind(R.id.bing_youfei)
    EditText bingYoufei;
    @Bind(R.id.et_oil)
    EditText etOil;
    @Bind(R.id.bing_guolufei)
    EditText bingGuolufei;
    @Bind(R.id.bing_fadan)
    EditText bingFadan;
    @Bind(R.id.bing_chuche)
    EditText bingChuche;
    @Bind(R.id.bing_huiche)
    EditText bingHuiche;
    @Bind(R.id.bing_otherfei)
    EditText bingOtherfei;
    @Bind(R.id.bing_shuoming)
    EditText bingShuoming;

    @Bind(R.id.cour_xiaofeiType)
    TextView xiaoFeiLeixing;

    @Bind(R.id.cour_guoluType)
    TextView gulufeiLeixing;

    @Bind(R.id.title_left)
    TextView title_left;

    private CourseDao courseDao;

    final String[] oilType = {"油库", "油卡", "现金"};//1:油库 2：油卡 3：现金
    final String[] roadPayType = {"ETC", "现金"};//2: ETC 3: 现金

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gufei_coure_acitivty);
        ButterKnife.bind(this);
        setTitle("行程信息");

        DaoSession daoSession = ((MyApplication) getApplication()).getDaoSession();
        courseDao = daoSession.getCourseDao();

    }

    @Override
    protected void onResume() {
        super.onResume();

        queryDataAndInitText();
    }

    /**
     * 为了点返回时保存数据
     *
     * @param view
     */
    @OnClick(R.id.title_left)
    public void titleLeftClick(View view) {
        saveInputData();
        super.fClick(view.getId());
    }

    private void queryDataAndInitText() {
        String jobId = SetData.getJobid();
        if (TextUtils.isEmpty(jobId)) {
            return;
        }

        QueryBuilder<Course> qb = courseDao.queryBuilder();
        qb.where(CourseDao.Properties.JobId.eq(jobId));
        List<Course> result = qb.list();
        if (result != null && result.size() > 0) {
            Course cou = result.get(0);

            bingYoufei.setText(cou.getOilMoney().equalsIgnoreCase("")?"0":cou.getOilMoney());
            bingGuolufei.setText(cou.getRoadToll().equalsIgnoreCase("")?"0":cou.getRoadToll());
            bingFadan.setText(cou.getTicket().equalsIgnoreCase("")?"0":cou.getTicket());
            bingChuche.setText(cou.getOutkm());
            bingHuiche.setText(cou.getReturnKm());
            bingOtherfei.setText(cou.getOtherPay().equalsIgnoreCase("")?"0":cou.getOtherPay());
            bingShuoming.setText(cou.getDescript());
            etOil.setText(cou.getOilNum().equalsIgnoreCase("")?"0":cou.getOilNum());

            if (cou.getOilType() != 0) {
                type = cou.getOilType();
                xiaoFeiLeixing.setText("消费类型 - " + oilType[cou.getOilType() - 1]);

            }

            if (cou.getRoadType() != 0) {
                type2 = cou.getRoadType();
                gulufeiLeixing.setText("过路费类型 - " + roadPayType[cou.getRoadType() - 2]);
            }

        } else {
            bingChuche.setText(SetData.getVehicleTotalKm());
        }
    }

    public static final int MILAGE = 500;
    @OnClick({R.id.cour_select1, R.id.cour_select2, R.id.course_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.cour_select1:
                show();
                break;
            case R.id.cour_select2:
                show1();
                break;
            case R.id.course_save:
                if (TextUtils.isEmpty(SetData.getJobid())) {
                    new MsgAlert().show("请先完成取车");
                    return;
                }
                if (type == 0) {
                    new MsgAlert().show("请选择消费类型");
                } else if (TextUtils.isEmpty(bingYoufei.getText().toString())) {
                    new MsgAlert().show("请输入油费金额");
                } else if (TextUtils.isEmpty(etOil.getText().toString())) {
                    new MsgAlert().show("请输入加油量");
                } else if (type2 == 0) {
                    new MsgAlert().show("请选择过路费类型");
                } else if (TextUtils.isEmpty(bingGuolufei.getText().toString())) {
                    new MsgAlert().show("请输入过路费金额");
                } else if (TextUtils.isEmpty(bingFadan.getText().toString())) {
                    new MsgAlert().show("请输入罚单金额");
                } else if (TextUtils.isEmpty(bingChuche.getText().toString())) {
                    new MsgAlert().show("请输入出车里程");
                } else if (TextUtils.isEmpty(bingHuiche.getText().toString())) {
                    new MsgAlert().show("请输入回车里程");
                } else {
                    try {
                        float huicheVal = Float.parseFloat(bingHuiche.getText().toString());
                        float chucheVal = Float.parseFloat(bingChuche.getText().toString());
                        if (TextUtils.equals(bingChuche.getText(), bingHuiche.getText())) {
                            new MsgAlert().show("回车里程需大于出车里程");
                            return;
                        }
                        if (huicheVal < chucheVal) {
                            new MsgAlert().show("回车里程小于出车里程");
                            return;
                        }
                        if (huicheVal - chucheVal>MILAGE) {
                            new MsgAlert().show("回车里程过大比出车里程多500km");
                            return;
                        }
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }

                    saveInputData();
                    RequeastBean bean =
                            new RequeastBean("save", "com.cygps.dubbo.WasteTransport.IRouteInfo",
                                    new GetCouseBean(bingYoufei.getText().toString(),
                                            type + "",
                                            bingGuolufei.getText().toString(),
                                            type2 + "",
                                            bingFadan.getText().toString(),
                                            bingChuche.getText().toString(),
                                            bingHuiche.getText().toString(),
                                            bingOtherfei.getText().toString(),
                                            bingShuoming.getText().toString(),
                                            etOil.getText().toString()
                                    ));
                    if (!DeviceUtil.isNetworkAvailable()) {//没用网络 缓存数据到内存
//                        MyApplication.netList.add(bean); bug001
                        DaoSession daoSession = ((MyApplication) getApplication()).getDaoSession();
                        RequestPersistent requestPersistent = new RequestPersistent();
                        requestPersistent.setServiceName(bean.serviceName);
                        requestPersistent.setServiceMethod(bean.serviceMethod);
                        requestPersistent.setServiceBody(new Gson().toJson(bean.serviceBody));
                        requestPersistent.setMethodClass(GetCouseBean.class.getName());
                        daoSession.getRequestPersistentDao().insertOrReplace(requestPersistent);
                        //new MsgAlert().show("现在没用网络，数据已保存 有网络的时候会自动提交");
                        finish();
                    } else {

                        ServerControl sc = new ServerControl(bean);
                        sc.serverListener = new ServerControl.ServerListener() {

                            @Override
                            public void serverFinish(ServerResult sr) {
                                if (sr.isContinue) {
                                    new MsgAlert().show("上传成功");
                                    finish();
                                }

                            }
                        };
                        new ProgressDialog(mContext).OKpost(sc);
                    }
                }
                break;
            default:
                break;

        }
    }


    public int type = 2;

    public void show() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        //    设置一个单项选择下拉框
        /**
         * 第一个参数指定我们要显示的一组下拉单选框的数据集合
         * 第二个参数代表索引，指定默认哪一个单选框被勾选上，1表示默认'女' 会被勾选上
         * 第三个参数给每一个单选项绑定一个监听器
         */
        builder.setSingleChoiceItems(oilType, 1, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                type = which + 1;
                Toast.makeText(CourseActivity.this, "选定为：" + oilType[which], Toast.LENGTH_SHORT).show();
                xiaoFeiLeixing.setText("消费类型 - " + oilType[which]);
                dialog.dismiss();
            }
        });

        builder.show();
    }

    public int type2 = 2;

    public void show1() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        //    设置一个单项选择下拉框
        /**
         * 第一个参数指定我们要显示的一组下拉单选框的数据集合
         * 第二个参数代表索引，指定默认哪一个单选框被勾选上，1表示默认'女' 会被勾选上
         * 第三个参数给每一个单选项绑定一个监听器
         */
        builder.setSingleChoiceItems(roadPayType, 1, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                type2 = which + 2;
                Toast.makeText(CourseActivity.this, "选定为：" + roadPayType[which], Toast.LENGTH_SHORT).show();
                gulufeiLeixing.setText("过路费类型 - " + roadPayType[which]);
                dialog.dismiss();
            }
        });

        builder.show();
    }


    @Override
    @OnFocusChange({R.id.bing_youfei, R.id.bing_guolufei, R.id.bing_fadan, R.id.bing_chuche,
            R.id.bing_huiche, R.id.bing_otherfei, R.id.bing_shuoming})
    public void onFocusChange(View v, boolean hasFocus) {
        if (!hasFocus) {
            saveInputData();

        }
    }

    private void saveInputData() {
        String jobId = SetData.getJobid();
        QueryBuilder<Course> qb = courseDao.queryBuilder();
        qb.where(CourseDao.Properties.JobId.eq(jobId));
        List<Course> result = qb.list();
        Course cou = null;
        if (result != null && result.size() > 0) {
            cou = result.get(0);
        } else {
            cou = new Course();
        }

        if (type != 0) {
            cou.setOilType(type);
        }

        if (type2 != 0) {
            cou.setRoadType(type2);
        }

        cou.setJobId(SetData.getJobid());
        cou.setOilMoney(bingYoufei.getText().toString());
        cou.setRoadToll(bingGuolufei.getText().toString());
        cou.setTicket(bingFadan.getText().toString());
        cou.setOutkm(bingChuche.getText().toString());
        cou.setReturnKm(bingHuiche.getText().toString());
        cou.setOtherPay(bingOtherfei.getText().toString());
        cou.setDescript(bingShuoming.getText().toString());
        cou.setOilNum(etOil.getText().toString());
        courseDao.save(cou);
    }
}
